package com.lut.edu.apm.commodityCenter.unit;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * http请求
 * @author Zhao Suzhen
 * @date `2024/4/13`
 */
public class RequestHTTPUtil {
    private final RestTemplate restTemplate;

    public RequestHTTPUtil() {
        this.restTemplate = new RestTemplate();
    }

    public String get(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            // Remove the trailing '&'
            sb.deleteCharAt(sb.length() - 1);
        }

        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
        return response.getBody();
    }

    public String post(String url, Map<String, String> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                map.add(entry.getKey(), entry.getValue());
            }
            // Remove the trailing '&'
            sb.deleteCharAt(sb.length() - 1);
        }

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), request, String.class);
        return response.getBody();
    }
}
